package com.maolong.api.index;


import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;

import java.io.IOException;

public class EsIndexUtils {
    private static final String HOST = "localhost";
    private static final int PORT = 9200;
    private static final String SCHEME = "http";
    private static RestHighLevelClient client;

    static {
        client=new RestHighLevelClient(
                RestClient.builder(new HttpHost(HOST,PORT,SCHEME)));
    }

    /**
     * 创建索引
     * @param indexName
     * @return
     */
    public static boolean createIndex(String indexName) {
        CreateIndexRequest request = new CreateIndexRequest(indexName);
        try {
            CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
            return createIndexResponse.isAcknowledged();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 返回索引
     * @param indexName
     * @return
     */
    public static GetIndexResponse getIndex(String indexName) {
        GetIndexRequest request = new GetIndexRequest(indexName);
        GetIndexResponse getIndexResponse = null;
        try {
            getIndexResponse = client.indices().get(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return getIndexResponse;
    }

    /**
     * 删除索引
     * @param indexName
     * @return
     */
    public static boolean delIndex(String indexName) {
        DeleteIndexRequest request = new DeleteIndexRequest(indexName);
        AcknowledgedResponse delete = null;
        try {
            delete = client.indices().delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return delete.isAcknowledged();
    }
}
